<?php

namespace app\home\controller;

use app\home\controller\City\Info;
use think\Config;
use think\Cookie;
use think\Request;
use think\Session;
use think\Controller;
use think\Db;
use app\home\common\Tools;
use app\home\service\AccountService;
use app\home\service\MiniappService;
use app\index\service\AppService;

class Index extends Controller
{
    private $MINI_ID;
    private $WX_id;
    private $WX_secret;
    private $TEMP_ID;

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $A = new AccountService();
        $this->MINI_ID = Session::get('login_miniID');
        $this->TEMP_ID = Session::get('login_tplID');
        $this->WX_id = $A->getminiAppsData('appid', $this->MINI_ID);
        $this->WX_secret = $A->getminiAppsData('secret', $this->MINI_ID);
    }

    public function index()
    {

        /* +++++++ 页面配置 +++++++ */
        $CONFIG = [
            'title' => '欢迎回来',
            'css' => [
                'home/css/plugins/morris/morris-0.4.3.min.css',
            ],
            'js' => [
                'home/js/plugins/flot/jquery.flot.js',
                'home/js/plugins/flot/jquery.flot.tooltip.min.js',
                'home/js/plugins/flot/jquery.flot.resize.js',
                'home/js/plugins/flot/jquery.flot.pie.js',
                'home/js/plugins/flot/jquery.flot.time.js',
            ]
        ];
        $this->assign('CONFIG', $CONFIG);

        $DATA = [  //  使用 MiniAppsService 调用小程序统计数据
            'newUser' => ['num' => '维护中', 'cp' => "0%"], // 新增用户
            'allUser' => ['num' => '维护中', 'cp' => "0%"], // 总用户数
            'shareTime' => ['num' => '维护中', 'cp' => "0%"], // 转发次数
            'sharePeople' => ['num' => '维护中', 'cp' => "0%"], // 转发人数
            'trendDATA' => $this->getAppTrend('week')
        ];

        $this->assign('DATA', $DATA);
        return $this->fetch('index');
    }

    /**
     * 获取小程序基础概括数据
     * @Xiao 2017年9月2日16:40:06 改写
     */
    private function getAppSurvey($miniID)
    {
        $today = date("Ymd", strtotime("-1 day"));
        $yesterday = date("Ymd", strtotime("-2 day"));
        $qiantian = date("Ymd", strtotime("-3 day"));

        $Service = new MiniappService();

        $today_array = $Service->userSum('sum', $miniID, $today);
        $yesterday_array = $Service->userSum('sum', $miniID, $yesterday);
        $qiantian_array = $Service->userSum('sum', $miniID, $qiantian);

        $newUser = $today_array['visit_total'] - $yesterday_array['visit_total'];   //新用户数
        $today_array['new_user'] = $newUser;
        $preNewUser = $yesterday_array['visit_total'] - $qiantian_array['visit_total'];   //昨天的新用户数
        $percent['new_user'] = round($newUser / ($preNewUser ? $preNewUser : 1) * 100);    //新用户增长率
        $percent['ave'] = round(($newUser + $preNewUser) / 2);

        $today_pv = $today_array['share_pv'] - $yesterday_array['share_pv'];
        $yesterday_pv = $yesterday_array['share_pv'] - $qiantian_array['share_pv'];
        $percent['share_pv'] = round($today_pv / ($yesterday_pv ? $yesterday_pv : 1) * 100);   //转发增长率

        $today_uv = $today_array['share_uv'] - $yesterday_array['share_uv'];
        $yesterday_uv = $yesterday_array['share_uv'] - $qiantian_array['share_uv'];
        $percent['share_uv'] = round($today_uv / ($yesterday_uv ? $yesterday_uv : 1) * 100);   //转发人增长率

        $sum = array();
        $sum[0] = $today_array;
        $sum[1] = $percent;

        return $sum;
    }

    /**
     * 获取小程序访问趋势数据
     * @xiao 2017年9月4日09:42:04  $dateType { data,week,month }
     */
    public function getAppTrend($dateType = null)
    {
        $Tools = new Tools();
        /* 条件判断 */
        if (!Request::instance()->has('dateType', 'get') and empty($dateType)) {
            return Request::instance()->isAjax() ? $Tools->error('request fail') : false; // 请求错误
        }
        $dateType = $dateType ? $dateType : $_GET['dateType'];
        $Service = new MiniappService();
        $data = [];
        switch ($dateType) {
            case 'day': // 日趋势
                $firstDay = $Service->getVisit('dayVisit', $this->MINI_ID, date('Ymd', strtotime("-1 day")));
                $lastDay = $Service->getVisit('dayVisit', $this->MINI_ID, date('Ymd', strtotime("-2 day")));
                $data = [ // 得出 打开次数及对比增长值 & 访问人数及对比增长值 & 新访问用户数及对比增长值 & 平均打开次数及对比增长值
                    'open_time' => $lastDay['session_cnt'] ? [$firstDay['session_cnt'], substr($lastDay['session_cnt'] / ($firstDay['session_cnt'] - $lastDay['session_cnt']) ? ($firstDay['session_cnt'] - $lastDay['session_cnt']) : 1, 0, 5)] : [0, 0],
                    'visit_people' => $lastDay['visit_uv'] ? [$firstDay['visit_uv'], substr($lastDay['visit_uv'] / ($firstDay['visit_uv'] - $lastDay['visit_uv']) ? ($firstDay['visit_uv'] - $lastDay['visit_uv']) : 1, 0, 5)] : [0, 0],
                    'visit_new_people' => $lastDay['visit_uv_new'] ? [$firstDay['visit_uv_new'], substr($lastDay['visit_uv_new'] / ($firstDay['visit_uv_new'] - $lastDay['visit_uv_new']) ? ($firstDay['visit_uv_new'] - $lastDay['visit_uv_new']) : 1, 0, 5)] : [0, 0],
                    'stay_time' => $lastDay['stay_time_session'] ? [$firstDay['stay_time_session'], substr($lastDay['stay_time_session'] / ($firstDay['stay_time_session'] - $lastDay['stay_time_session']) ? ($firstDay['stay_time_session'] - $lastDay['stay_time_session']) : 1, 0, 5)] : [0, 0]
                ];
                break;
            case 'week': // 周趋势
                $firstWeek = $Service->getVisit('weekVisit', $this->MINI_ID, date('Ymd', strtotime((date("w") > 1 ? '-2' : '-1') . ' monday', time())), date('Ymd', strtotime('-1 sunday', time())));
                $lastWeek = $Service->getVisit('weekVisit', $this->MINI_ID, date('Ymd', strtotime((date("w") > 1 ? '-3' : '-2') . ' monday', time())), date('Ymd', strtotime('-2 sunday', time())));
//                return [$firstWeek,$lastWeek];
//
                $data = [ // 得出 打开次数及对比增长值 & 访问人数及对比增长值 & 新访问用户数及对比增长值 & 平均打开次数及对比增长值
                    'open_time' => 1,//$lastWeek['session_cnt'] ? [$firstWeek['session_cnt'], substr($lastWeek['session_cnt'] / ($firstWeek['session_cnt'] - $lastWeek['session_cnt']) ? ($firstWeek['session_cnt'] - $lastWeek['session_cnt']) : 1, 0, 5)] : [0, 0],
                    'visit_people' => 1,//$lastWeek['visit_uv'] ? [$firstWeek['visit_uv'], substr($lastWeek['visit_uv'] / ($firstWeek['visit_uv'] - $lastWeek['visit_uv'] > 0) ? ($firstWeek['visit_uv'] - $lastWeek['visit_uv']) : 1, 0, 5)] : [0, 0],
                    'visit_new_people' => 1, // $lastWeek['visit_uv_new'] ? [$firstWeek['visit_uv_new'], substr($lastWeek['visit_uv_new'] / ($firstWeek['visit_uv_new'] - $lastWeek['visit_uv_new']) ? ($firstWeek['visit_uv_new'] - $lastWeek['visit_uv_new']) : 1, 0, 5)] : [0, 0],
                    'stay_time' => 1,//$lastWeek['stay_time_session'] ? [$firstWeek['stay_time_session'], substr($lastWeek['stay_time_session'] / ($firstWeek['stay_time_session'] - $lastWeek['stay_time_session']) ? ($firstWeek['stay_time_session'] - $lastWeek['stay_time_session']) : 1, 0, 5)] : [0, 0]
                ];
                break;
            case 'month': // 月趋势
                $firstMonth = $Service->getVisit('monthVisit', $this->MINI_ID, date('Ymd', strtotime('-1 month', strtotime(date('Y-m', time()) . '-01 00:00:00'))), date('Ymd', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400));
                $lastMonth = $Service->getVisit('monthVisit', $this->MINI_ID, date('Ymd', strtotime('-2 month', strtotime(date('Y-m', time()) . '-01 00:00:00'))), date('Ymd', strtotime(date('Y-m', time()) . '-01 00:00:00') - 86400 * 2));
                $data = [ // 得出 打开次数及对比增长值 & 访问人数及对比增长值 & 新访问用户数及对比增长值 & 平均打开次数及对比增长值？
                    'open_time' => $lastMonth['session_cnt'] ? [$firstMonth['session_cnt'], substr($lastMonth['session_cnt'] / ($firstMonth['session_cnt'] - $lastMonth['session_cnt']) ? ($firstMonth['session_cnt'] - $lastMonth['session_cnt']) : 1, 0, 5)] : [0, 0],
                    'visit_people' => $lastMonth['visit_uv'] ? [$firstMonth['visit_uv'], substr($lastMonth['visit_uv'] / ($firstMonth['visit_uv'] - $lastMonth['visit_uv']) ? ($firstMonth['visit_uv'] - $lastMonth['visit_uv']) : 1, 0, 5)] : [0, 0],
                    'visit_new_people' => $lastMonth['visit_uv_new'] ? [$firstMonth['visit_uv_new'], substr($lastMonth['visit_uv_new'] / ($firstMonth['visit_uv_new'] - $lastMonth['visit_uv_new']) ? ($firstMonth['visit_uv_new'] - $lastMonth['visit_uv_new']) : 1, 0, 5)] : [0, 0],
                    'stay_time' => $lastMonth['stay_time_session'] ? [$firstMonth['stay_time_session'], substr($lastMonth['stay_time_session'] / ($firstMonth['stay_time_session'] - $lastMonth['stay_time_session']) ? ($firstMonth['stay_time_session'] - $lastMonth['stay_time_session']) : 1, 0, 5)] : [0, 0]
                ];
                break;
        }
        if ($data) {
            return Request::instance()->isAjax() ? $Tools->success('request success', $data) : $data; // 请求错误
        }
        return Request::instance()->isAjax() ? $Tools->error('request lost') : false; // 请求错误
    }

    /*
     * 获取小程序用户画像数据 Ajax
     * @Xiao 2017年9月5日09:32:06
     */
    public function getAppUserPort()
    {
        $Tools = new Tools();
        /* 条件判断 */
        if (!Request::instance()->isAjax() or !Request::instance()->has('Type', 'get') or !Request::instance()->has('dateType', 'get')) {
            return $Tools->error('request fail'); // 请求错误
        }
        $Type = $_GET['Type'] == 'new' ? 'new' : 'live'; // 指定类型
        $dateType = $_GET['dateType']; // 指定时间区段查询
        $startTime = $dateType == 'day' ? 1 : ($dateType == 'week' ? 7 : 30); // 开始时间
        $Service = new MiniappService();
        $ages = $Service->getUserPort($Type, $this->MINI_ID, date('Y-m-d', strtotime("-" . $startTime . " day")), date('Y-m-d', strtotime("-1 day")))['ages'];
        $sexs = $Service->getUserPort($Type, $this->MINI_ID, date('Y-m-d', strtotime("-" . $startTime . " day")), date('Y-m-d', strtotime("-1 day")))['genders'];
        if ($ages and $sexs) {
            return $Tools->success('request success', [
                'ages' => $ages,
                'sexs' => $sexs
            ]);     //  请求错误
        }
        return $Tools->error('request lost'); // 请求错误
    }

    public function add_jsoninfo()
    {
        $template_id = $this->TEMP_ID;
        $miniapp_id = $this->MINI_ID;
        $appinfo = new AppService();
        $addinfo = $appinfo->add_extjson($miniapp_id, $template_id);
        $addinfo['ver'] = 'suYong-V.' . substr(strtoupper(md5($this->MINI_ID . rand(10000, 99999) . $this->TEMP_ID)), 0, 8);
        return $addinfo;
    }

    public function add_json()
    {
        $template_id = $this->TEMP_ID;
        $miniapp_id = $this->MINI_ID;
        $version = input('post.version');
        $describe = input('post.describe');
        $data = input('post.data');
        $doappinfo = new AppService();
        $doadd = $doappinfo->upload_code($template_id, $data, $version, $describe, $miniapp_id);
        return $doadd;

    }

    public function subcheck()
    {
        $app_id = $this->MINI_ID;
        $temp_id = $this->TEMP_ID;
        $subcheck = new AppService();
        $sub = $subcheck->get_submit_audit($app_id, $temp_id);
        $code = $subcheck->check_code($sub['id'], $app_id);
        return $code;
    }


    public function submit_code()
    {
        $data = input('post.data');
        $id = input('post.id');
        $submit_code = new AppService();
        $sub = $submit_code->submit_audit($data, $id, $this->MINI_ID);
        return $sub;
    }


    public function sub_publish()
    {
        $app_id = $this->MINI_ID;
        $temp_id = $this->TEMP_ID;
        $subpub = new AppService();
        $temp_id = $subpub->get_submit_audit($app_id, $temp_id);
        $subapp = $subpub->submit_publish($temp_id);
        return $subapp;
    }


    public function ceshi()
    {
        $res = Db::table('wyz_admin_template')->where('miniapps_id', $this->MINI_ID)->select();
        dump($res);
    }

}
